<?php

/**
 * workflow actions.
 *
 * @package    Wildlive
 * @subpackage workflow
 * @author     Maximilian Lenkeit <dev@lenki.com>
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class workflowActions extends WildliveActions
{

  /**
   * Executes index action
   *
   * @param sfRequest $request A request object
   */
  public function executeIndex (sfWebRequest $request)
  {
    $workflow_instances = wfWorkflowInstanceTable::getInstance()->findAll();
    $workflows = array();
    foreach ($workflow_instances as $workflow_instance)
    {
      $workflows[] = new ExecutableWorkflow($workflow_instance);
    }
    $this->workflows = $workflows;
  }

  public function executeInbox (sfWebRequest $request)
  {
    $work_items = wfWorkflowWorkItemTable::getInstance()->retrieveForInbox($this->getUser()
      ->getGuardUser());
    $run_time_work_items = array();
    foreach ($work_items as $work_item)
    {
      $run_time_work_items[] = RunTimeWorkflowNodeFactory::getInstance()->create($work_item);
    }
    
    $this->work_items = $run_time_work_items;
  }

  public function executeShowWorkItem(sfWebRequest $request)
  {
    $this->executeInbox($request);
    
    $this->current_work_item = RunTimeWorkflowNodeFactory::getInstance()->create($this->getRoute()->getObject());
    
    // Update is_read
    $object = $this->current_work_item->getObject();
    $object->setIsRead(true);
    $object->save();
    
    $this->setTemplate('inbox');
  }

  public function executeAjaxShowWorkItem(sfWebRequest $request)
  { 
    $current_work_item = RunTimeWorkflowNodeFactory::getInstance()->create($this->getRoute()->getObject());
    
    // Update is_read
    $object = $current_work_item->getObject();
    $object->setIsRead(true);
    $object->save();
    
    return $this->renderPartial('workflow/inbox_message_view', array('current_work_item' => $current_work_item));
  }

  public function executeWorkItemAction (sfWebRequest $request)
  {
    try
    {
      $node = RunTimeWorkflowNodeFactory::getInstance()->create($this->getRoute()
        ->getObject());
      $node->execute($this->getRoute()
        ->getActionIdentifier());
      $this->getUser()
        ->setFlash(UserFlash::SUCCESS, 'Aktion erfolgreich durchgeführt.');
    }
    catch (WorkflowException $e)
    {
      $this->getLogger()
        ->emerg($e);
      $this->getUser()
        ->setFlash(UserFlash::ERROR, 'Es ist ein Fehler aufgetreten, die Aktion wurde nicht durchgeführt.');
    }
    $this->redirect($this->generateUrl('homepage'));
  
  }
}
